<?php

namespace App\Http\Rest\Information;

use App\Constants\Common\HttpStatusCode;
use App\Exceptions\IllegalRequestException;
use Framework\Foundation\Config;
use Framework\Foundation\Request\ServerRequest;
use Framework\Foundation\Response\ResponseGen;
use Framework\Foundation\Rest\ResourceConverter;
use Framework\Foundation\Rest\RestRequestInfo;
use Psr\Http\Message\ServerRequestInterface;
use Framework\Foundation\Route\RouterHelper;
use Psr\Http\Message\ResponseInterface;

/**
 * Class AdminRestControl
 * @package App\Http\Rest\Admin
 * @link http://pagination.js.org/  pagenation文档
 */
class InformationRestControl
{
    /**
     * @param ServerRequest $request
     * @return mixed
     * @throws IllegalRequestException
     */
    public function index(ServerRequestInterface $request)
    {
        /**
         * @var $restRequestInfo RestRequestInfo;
         */
        $restRequestInfo = $request->getAttribute('restRequestInfo');
        $targetInfo = $this->mapResource($restRequestInfo->getRestTargetInfo());

        $className = "\App\Http\Rest\Information\Resource\\" . $targetInfo['object'];
  
//        if (!$this->checkAllowed($targetInfo['object'])) {
//            throw new IllegalRequestException("拒绝访问，资源未授权", HttpStatusCode::FORBIDDEN);
//        }

        if (class_exists($className)) {
            $obj = new $className;
        } else {
            $obj = new BaseResource;
        }

        return  call_user_func([$obj, $targetInfo['action']], $targetInfo, $request);
    }

    public function checkAllowed($targetSource)
    {
        $allowed = Config::instance()->get('rest/client.allowed');
        return in_array($targetSource, $allowed['resource']);
    }


    public function mapResource($targetInfo)
    {
        $map = [
            'permission' => 'rbac_permission',
            'role' => 'rbac_role',
            'role_permission' => 'rbac_role_permission',
            'user_role' => 'rbac_user_role',
        ];

        if (isset($map[$targetInfo['resource']])) {
            $targetInfo['resource'] = $map[$targetInfo['resource']];
        }

        return $targetInfo;
    }
}
